package com.example.yuntiku.Servlet;

import com.example.yuntiku.Service.QuestionService;
import com.example.yuntiku.entity.Question;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet(name = "insertServlet", value = "/insertServlet")
public class insertServlet extends HttpServlet {
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        QuestionService questionService = new QuestionService();
        String[] optionsArr = new String[4];
        for(int k = 30; k <= 46; k++) {
            // 内层循环，每个二级知识点20个题
            for(int i = 0; i < 20; i++) {
                Question question = new Question();

                // 生成两个随机数
                int num1 = (int)(1+Math.random()*9); // 生成 1 - 10 的随机数
                int num2 = (int)(1+Math.random()*9); // 生成 1 - 10 的随机数

                question.setContent(num1 + " 加上 " + num2 + " 等于多少？");

                // 产生随机的正确答案的位置：
                int correctOptionIndex = (int)(Math.random()*4);
                optionsArr[correctOptionIndex] = String.valueOf(num1+num2);

                // 填充其他错误答案：
                for (int j=0; j<4; j++){
                    if (j != correctOptionIndex){ //确保我们不覆盖正确答案
                        optionsArr[j] = String.valueOf(num1+num2+j+1);
                    }
                }
                // 设定选项和答案：
                question.setOption_a("A. " + optionsArr[0]);
                question.setOption_b("B. " + optionsArr[1]);
                question.setOption_c("C. " + optionsArr[2]);
                question.setOption_d("D. " + optionsArr[3]);

                // 正确答案应该是 'A'、'B'、'C'、'D' 中的一个：
                char answer = (char) ('A' + correctOptionIndex);
                question.setAnswer(String.valueOf(answer));

                question.setResolution("解析");
                question.setPraise(0);
                question.setStep(i + 1);
                question.setSection(2);
                question.setKnowledgeone(8);
                question.setKnowledgetwo(k);

                // 直接调用insertQuestion 方法将生成的 question 对象插入数据库
                questionService.insertQuestion(question);
            }
        }

        request.getRequestDispatcher("insertqu.jsp").forward(request,response);
    }
}